const colorPicker = document.querySelector("input");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

function init() {
  const w = 500,
    h = 300;
  canvas.width = w * devicePixelRatio;
  canvas.height = h * devicePixelRatio;

  canvas.style.width = w + "px";
  canvas.style.height = h + "px";
}

init();

const shapes = [];

class Rectangle {
  constructor(color, startX, startY) {
    this.color = color;
    // 起始坐标
    this.startX = startX;
    this.startY = startY;
    // 结束坐标
    this.endX = startX;
    this.endY = startY;
  }

  get minX() {
    return Math.min(this.startX, this.endX);
  }

  get maxX() {
    return Math.max(this.startX, this.endX);
  }
  get minY() {
    return Math.min(this.startY, this.endY);
  }
  get maxY() {
    return Math.max(this.startY, this.endY);
  }

  draw() {
    ctx.beginPath();
    ctx.moveTo(this.minX * devicePixelRatio, this.minY * devicePixelRatio);
    ctx.lineTo(this.maxX * devicePixelRatio, this.minY * devicePixelRatio);
    ctx.lineTo(this.maxX * devicePixelRatio, this.maxY * devicePixelRatio);
    ctx.lineTo(this.minX * devicePixelRatio, this.maxY * devicePixelRatio);
    ctx.lineTo(this.minX * devicePixelRatio, this.minY * devicePixelRatio);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.strokeStyle = "#fff";
    ctx.lineCap = "square";
    ctx.lineWidth = 3 * devicePixelRatio;
    ctx.stroke();
  }

  isInside(x, y) {
    return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;
  }
}

canvas.onmousedown = (e) => {
  const rect = canvas.getBoundingClientRect();
  const clickX = e.clientX - rect.left;
  const clickY = e.clientY - rect.top;
  const clickedShape = getShape(clickX, clickY);
  if (clickedShape) {
    // 存在就拖动
    const { startX, startY, endX, endY } = clickedShape;
    window.onmousemove = (e) => {
      // 获取鼠标移动距离
      const disX = e.clientX - rect.left - clickX;
      const disY = e.clientY - rect.top - clickY;
      // 更新坐标
      clickedShape.startX = startX + disX;
      clickedShape.endX = endX + disX;
      clickedShape.startY = startY + disY;
      clickedShape.endY = endY + disY;
    };
  } else {
    // 不存在就新建
    const shape = new Rectangle(colorPicker.value, clickX, clickY);
    shapes.push(shape);
    window.onmousemove = (e) => {
      shape.endX = e.clientX - rect.left;
      shape.endY = e.clientY - rect.top;
      draw();
    };
  }
  window.onmouseup = () => {
    window.onmousemove = null;
    window.onmouseup = null;
  };
};

// 辅助函数-获取点中的图形
function getShape(x, y) {
  // 倒序循环, 因为后画的图形是在先画的图形之上的
  for (let i = shapes.length - 1; i >= 0; i--) {
    const shape = shapes[i];
    if (shape.isInside(x, y)) {
      return shape;
    }
  }
  return null;
}
// 绘制图形
function draw() {
  requestAnimationFrame(draw);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (const shape of shapes) {
    shape.draw();
  }
}
